﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cstdx.Internal;


public static class HexConverter
{
	/// <summary>
	/// 16进制字符串转字节数组
	/// </summary>
	/// <param name="hexStr">16进制字符串</param>
	/// <returns>转换后的字节数组，转换失败返回null</returns>
	public static byte[] HexString2Bytes(string hexStr)
	{
		// 移除字符串中的所有空格
		hexStr = hexStr.Replace(" ", "");

		try
		{
			// 转换16进制字符串为字节数组
			byte[] data = new byte[hexStr.Length / 2];
			for (int i = 0; i < data.Length; i++)
			{
				int index = i * 2;
				data[i] = Convert.ToByte(hexStr.Substring(index, 2), 16);
			}
			return data;
		}
		catch (Exception ex)
		{
			// 处理转换错误
			Console.WriteLine(ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 字节数组转16进制字符串
	/// </summary>
	/// <param name="bytes">字节数组</param>
	/// <returns>带空格分隔的16进制字符串</returns>
	public static string Bytes2HexString(byte[] bytes)
	{
		// 将字节数组格式化为带空格分隔的16进制字符串
		StringBuilder sb = new StringBuilder();
		foreach (byte b in bytes)
		{
			sb.AppendFormat("{0:X2} ", b);
		}
		// 移除末尾多余的空格
		return sb.ToString().TrimEnd();
	}
}


